import { Singleton } from "./Utils";


/**
 * 注册组件的类型装饰器
 */
export function RegComponentType() {
	return function (target) {

		const id = EcsComponent.__next_gen_id++

		Object.defineProperty(
			target,
			'__compId',
			{
				value: id,
				writable: false,
				enumerable: false
			}
		)
		if (!EcsComponent.__types[id]) {
			EcsComponent.__types[id] = target;
		}
	}
}
/**
 * 组件的属性标记为对象型，以便重置的时候进行深拷贝
 */
export function RegObjProp() {
	return function (target: any, propertyKey: string) {
		if (!target.constructor.__objPropKeys) {
			target.constructor.__objPropKeys=[]
		}
		target.constructor.__objPropKeys.push(propertyKey)
	}
}

/**Ecs组件
 * !注意组件的每个属性必须有默认值，不然回收后不能重置该属性
 */
export class EcsComponent extends Singleton {
	public __enable: boolean = true;
	public __ownerId: number = 0;

	public static __next_gen_id = 0
	/**已经注册的组件类型 */
	public static __types: { [id: number]: new (...args: any[]) => EcsComponent } = {};

	static getIdFromClz<T extends (EcsComponent)>(compClz: new () => T): number {
		return (compClz as any).__compId
	}


	static getId(comp: EcsComponent): number {
		return (comp.constructor as any).__compId
	}

	public static getComponentType(id: number): new (...args: any[]) => EcsComponent {
		return this.__types[id];
	}

	/**重置组件id生成器,在一个ECS组件定义文件中开始注册组件前调用 */
	public static resetGenId() {
		this.__next_gen_id = 0
	}

	public static resetComp(comp: EcsComponent, cst: any) {
        const instance = cst.instance()

        Object.assign(comp, instance)

        if (cst.__objPropKeys) {

            cst.__objPropKeys.forEach(key => {
                comp[key] = JSON.parse(JSON.stringify(instance[key]))
            });
        }
    }
}